package com.github.freegeese.maven.plugin.autocode.demo.base;

/**
 * 可排序的Service
 *
 * @param <M>
 * @param <E>
 * @param <ID>
 */
public class SortableService<M extends SortableMapper<E, ID>, E extends Sortable<ID>, ID> extends BaseService<M, E, ID> {
    /**
     * 移动位置
     */
    public enum Position {
        TOP,    // 移动到第一行
        UP,     // 往上移动一行
        DOWN,   // 往下移动一行
        BOTTOM  // 移动到最后一行
    }

    public int exchange(E source, E target) {
        return getMapper().exchange(source, target);
    }

    public int move(E from, E to) {
        return getMapper().move(from, to);
    }

    public int top(E entity) {
        return move(entity, Position.TOP);
    }

    public int up(E entity) {
        return move(entity, Position.UP);
    }

    public int down(E entity) {
        return move(entity, Position.DOWN);
    }

    public int bottom(E entity) {
        return move(entity, Position.BOTTOM);
    }

    protected int move(E from, Position position) {
        M mapper = getMapper();
        E to = null;
        switch (position) {
            case TOP:
                to = mapper.selectFirst();
                break;
            case UP:
                to = mapper.selectPrevious(from);
                break;
            case DOWN:
                to = mapper.selectNext(from);
                break;
            case BOTTOM:
                to = mapper.selectLast();
                break;
        }
        // 没有找到目标行（两种可能：1.当前行在顶部，向上移动 2.当前行在底部，向下移动）
        if (null == to) {
            return 0;
        }
        // 同一行记录
        if (to.getId().equals(from.getId())) {
            return 0;
        }
        return mapper.move(from, to);
    }
}
